/*
 * @Author: CodeHare
 * @Date: 2023-10-09 09:39:35
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-05-15 17:14:40
 * @Description: 充电桩设备
 */

import 'dart:async';
import 'dart:math';
// import 'dart:math';
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/text_width.dart';
import 'package:yt_devops/components/timer_picker.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/model/device_obj/product_config_model.dart';
import 'package:yt_devops/pages/devices/device_controll/device_controll_utils.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/char_x.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/new_air_cooling_page_model.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/charging_station/charging_station_model.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

class ChargingStationController extends GetxController
    with GetTickerProviderStateMixin {
  // RefreshController refreshController =
  //     RefreshController(initialRefresh: false);
  final NewAirCoolingPageModel newAirCoolingPageModel =
      NewAirCoolingPageModel();

  final DeviceServices deviceServices = Get.find<DeviceServices>();
  final ChargingStationModel state = ChargingStationModel();
  // ChargeTerminalTrend chargeTerminalTrendModel = ChargeTerminalTrend();
  StreamController<Map<String, dynamic>>? streamController;
  int? trendDeviceId;
  int? deviceId;
  Color? titleColor = Colour.mainTextColor;
  String? terminalName = "";
  IconData arrowDirection = Icons.keyboard_arrow_down;
  bool expand = false;
  int selectedIndex = 0;
  bool selected = false;
  double containerWidth = 100;
  // 设备基础信息
  DeviceModel? deviceModel;
  List<PopupMenuItem> actionList = [];
  List<String> showListString = [];

  /// 远程控制指令
  Map remoteControlMap = {};

  /// 配置信息
  Map configMap = {};

  /// 页面信息
  Map pageMap = {};

  /// 图表组件id
  String? chartId;

  ///
  UseSubsribe subsribe =
      UseSubsribe(isContainDeviceId: true, isMultipleDevice: true);

  /// 目标展示时间
  late DateTime target;
  late int targetYear;
  late int targetMonth;
  late int targetDay;

  /// 目标展示趋势时间
  late DateTime trendTarget;
  late int trendTargetYear;
  late int trendTargetMonth;
  late int trendTargetDay;
  StatisticUnitStatusType statisticUnitType = StatisticUnitStatusType.day;
  String orderCount = '';
  String chargeTime = '';
  String chargeElectricity = '';
  String orderAmount = '';
  Future<void> initData() async {
    initCurrentDate();
    initTimeList();
    await loadRealTimePowerData();
    if (chartId != 'Charge') await getTerminalDevice();
    await loadChargingTrendData();
  }

  onClickTab(StatisticUnitStatusType type) async {
    statisticUnitType = type;
    if (type == StatisticUnitStatusType.day) {
      state.pickerMode = DateTimePickerMode.day;
    } else if (type == StatisticUnitStatusType.month) {
      state.pickerMode = DateTimePickerMode.month;
    } else {
      state.pickerMode = DateTimePickerMode.year;
    }
    await loadChargingTrendData();
    update();
  }

  @override
  void onReady() {}

  @override
  void onClose() {
    streamController?.close();
    subsribe.closeListen();
  }

  /// @description: 请求实时功率数据
  /// @return {*}
  Future<void> loadRealTimePowerData(
      {RefereshType refereshType = RefereshType.refresh}) async {
    await Configs.httpClient.requestWithLoading(() async {
      var params = {
        'deviceId': deviceModel!.deviceId,
        'date': '$targetYear-$targetMonth-$targetDay'
      };
      var data = await deviceServices.getChargeStationRealTimePower(params);
      state.chaStaRealPower = List.of(data['list'])
          .map((e) => ChaStaRealPower.fromJson(e))
          .toList();
      assignChaStaRealPower();
    }, onError: (error) {
      // refreshController.loadFailed();
      return true;
    }, showLoading: false);
  }

  /// @description: 请求充电趋势/终端趋势数据
  /// @return {*}
  Future<void> loadChargingTrendData(
      {RefereshType refereshType = RefereshType.refresh}) async {
    await Configs.httpClient.requestWithLoading(() async {
      var params = {
        'deviceId': chartId == 'Charge' ? deviceModel!.deviceId : trendDeviceId,
        'date': '$trendTargetYear-$trendTargetMonth-$trendTargetDay',
        'type': statisticUnitType.value,
      };
      Log.d('params===' + params.toString());
      var data =
          await deviceServices.getDailyChargeCapacityAndFrequency(params);
      // Log.d('data==========' + data.toString());
      // chargeTerminalTrendModel = ChargeTerminalTrend.fromJson(data);
      Log.d('ChargeTerminalTrend=========');
      assignChaStaChargingTrend(data);
    }, onError: (error) {
      // refreshController.loadFailed();
      return true;
    }, showLoading: false);
  }

  // getSubDevice
  /// @description: 请求终端设备列表
  /// @return {*}
  Future<void> getTerminalDevice(
      {RefereshType refereshType = RefereshType.refresh}) async {
    await Configs.httpClient.requestWithLoading(() async {
      var data = await deviceServices
          .getChargeTerminalDevice({"deviceId": deviceModel!.deviceId});
      state.terminalDeviceOriginList =
          List.of(data).map((e) => ChargingSubDevice.fromJson(e)).toList();

      trendDeviceId = state.terminalDeviceOriginList[0].deviceId;
      assignTerminalList();
    }, onError: (error) {
      // refreshController.loadFailed();
      return true;
    }, showLoading: false);
  }

  /// @description: 赋值终端列表
  /// @return {*}
  void assignTerminalList() {
    Log.d('assignTerminalList=');
    if (state.terminalDeviceOriginList.isEmpty) return;
    state.terminalDeviceList.clear();
    double maxWidth = 100;
    List<double> widthList = [];
    for (var i = 0; i < state.terminalDeviceOriginList.length; i++) {
      state.terminalDeviceList.add(ItemEntity(
        key: state.terminalDeviceOriginList[i].deviceId!.toString(),
        name: state.terminalDeviceOriginList[i].name!,
        value: i.toString(),
      ));
      widthList.add(TextWidth.calculateTextSize(
          '${state.terminalDeviceOriginList[i].name!}:',
          ytTextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w400,
            color: titleColor,
          )));
    }
    widthList.sort((a, b) => a.compareTo(b));
    containerWidth = widthList.last;
    Log.d('maxWidth=' + maxWidth.toString());
    terminalName = state.terminalDeviceList[0].name;
    update();
  }

  void onClickTerminalTitle() {
    titleColor = titleColor == Colour.primaryColor
        ? Colour.mainTextColor
        : Colour.primaryColor;
    arrowDirection = arrowDirection == Icons.keyboard_arrow_down
        ? Icons.keyboard_arrow_up
        : Icons.keyboard_arrow_down;

    expand = !expand;
    update();
  }

  /// @description: 赋值充电桩实时功率
  /// @return {*}
  void assignChaStaChargingTrend(data) {
    if (data != null) {
      if (data['chargeCountTotal'] != null) {
        orderCount = data['chargeCountTotal'].toStringAsFixed(0);
      }
      if (data['todayChargeTime'] != null) {
        chargeTime = data['todayChargeTime'].toStringAsFixed(0);
      }
      if (data['chargeElectricityTotal'] != null) {
        chargeElectricity = data['chargeElectricityTotal'].toStringAsFixed(2);
      }
      if (data['todayMoney'] != null) {
        orderAmount = data['todayMoney'].toStringAsFixed(2);
      }
      if (data['list'] != null) {
        var list = data['list'];
        if (list!.isEmpty) return;
        state.chargingOrderCount.clear();
        state.trendsTimeList.clear();
        state.chargingTimes.clear();
        state.chargingCapacityList.clear();
        state.chargingFee.clear();
        // List<num> tempList = [];
        for (var i = 0; i < list.length; i++) {
          state.chargingCapacityList.add(list[i]['chargeElectricity'] ?? '--');
          state.chargingOrderCount.add(list[i]['chargeCount'] ?? '--');
          state.chargingTimes.add(list[i]['chargeDuration'] ?? '--');
          state.chargingFee.add(list[i]['chargeMoney'] ?? '--');
          state.trendsTimeList
              .add(_getShowTime(list[i]['time'], statisticUnitType));
          // if (list[i]['chargeElectricity'] != null) {
          //   tempList.add(list[i]['chargeElectricity']);
          // }
          // if (list[i]['chargeCount'] != null) {
          //   tempList.add(list[i]['chargeCount']);
          // }
          // if (list[i]['chargeDuration'] != null) {
          //   tempList.add(list[i]['chargeDuration']);
          // }
          // if (list[i]['chargeMoney'] != null) {
          //   tempList.add(list[i]['chargeMoney']);
          // }
        }
        // if (tempList.isNotEmpty) {
        // electricityMaxValue = tempList.reduce(max);
        // electricityMinValue = tempList.reduce(min);
        // }

        // Log.d('electricityMaxValue===' + electricityMaxValue.toString());
      }
      update();
    }
  }

  _getShowTime(
      String? timeString, StatisticUnitStatusType statisticUnitStatusType) {
    String time = timeString.toString();

    if (statisticUnitStatusType == StatisticUnitStatusType.day &&
        timeString.toString().length > 16) {
      time = timeString.toString().substring(10, 16);
    } else if (statisticUnitStatusType == StatisticUnitStatusType.month &&
        timeString.toString().length >= 10) {
      time = timeString.toString().substring(8, 10);
    } else if (statisticUnitStatusType == StatisticUnitStatusType.year &&
        timeString.toString().length >= 7) {
      time = timeString.toString().substring(5, 7);
    }
    Log.d('time===' + time.toString());
    return time;
  }

  /// @description: 赋值充电趋势/终端趋势数据
  /// @return {*}
  void assignChaStaRealPower() {
    state.chaStaPowerDataList.clear();
    state.powerUseRateList.clear();
    state.powerTimeList.clear();
    // List<num> tempList = [];
    for (var i = 0; i < state.chaStaRealPower.length; i++) {
      state.chaStaPowerDataList.add(
        state.chaStaRealPower[i].power ?? '--',
      );
      state.powerUseRateList.add(
        state.chaStaRealPower[i].powerUseRate ?? '--',
      );
      state.powerTimeList.add(
        state.chaStaRealPower[i].getTime,
      );
      // if (state.chaStaRealPower[i].power != null) {
      //   tempList.add(state.chaStaRealPower[i].power!);
      // }
      // if (state.chaStaRealPower[i].powerUseRate != null) {
      //   tempList.add(state.chaStaRealPower[i].powerUseRate!);
      // }
    }
    // if (tempList.isNotEmpty) {
    // powerMinValue = tempList.reduce(max);
    // }
    Log.d(' 111loadRealTimePowerData==' + state.powerTimeList.toString());
    update();
  }

  /// @description: 时间选择器选择后回显时间到按钮
  /// @return {*}
  void echoRealTimePowerDate(DateTime date) {
    target = date;
    targetYear = target.year;
    targetMonth = target.month;
    targetDay = target.day;

    loadRealTimePowerData();
    update();
  }

  /// @description: 时间选择器选择后回显时间到按钮
  /// @return {*}
  void echoChageTrendDate(DateTime date, StatisticUnitStatusType type) {
    statisticUnitType = type;

    trendTarget = date;
    trendTargetYear = trendTarget.year;
    trendTargetMonth = trendTarget.month;
    trendTargetDay = trendTarget.day;

    loadChargingTrendData();
    update();
  }

  /// @description: 单位数前置加零
  /// @return {*}
  String addLeadingZero(String? value) {
    if (value!.length == 1) {
      return '0$value';
    }

    return value;
  }

  /// @description: 初始化当前日期
  /// @return {*}
  void initCurrentDate() {
    target = trendTarget = DateTime.now();
    targetYear = trendTargetYear = target.year;
    targetMonth = trendTargetMonth = target.month;
    targetDay = trendTargetDay = target.day;
  }

  ///设置默认的x轴数据
  initTimeList() {
    // List<int> hoursArray = List.generate(24, (index) => index);
    // for (var element in hoursArray) {
    //   String hourString = element.toString();
    //   if(element < 10){
    //     hourString =  '0$hourString';
    //   }
    //   state.powerTimeList.add('$hourString:00');
    //   state.trendsTimeList.add('$hourString:00');
    // }
    state.trendsTimeList = ChartXDate.getHoursData();
    state.powerTimeList = ChartXDate.getHoursData();
  }

  /// @description: 下拉刷新
  /// @return {*}
  void onRefresh() async {
    await loadRealTimePowerData();
    if (chartId != 'Charge') await getTerminalDevice();
    await loadChargingTrendData();

    endRefresh();
  }

  /// @description: 刷新结束
  /// @return {*}
  void endRefresh() {
    // if (refreshController.isRefresh) {
    //   refreshController.refreshCompleted();
    // }
  }

  Future getOssPhysicalModel(int? deviceId) async =>
      await Configs.httpClient.requestWithLoading(() async {
        var result = await deviceServices
            .getDeviceNewProperty({'deviceId': deviceId, 'platform': 1});
        Log.d('result===' + result.toString());
        showListString.clear();
        actionList.clear();
        if (result?['data'] is List) {
          for (var element in result?['data']) {
            if (element['id'] == 'remoteControl' &&
                !FuncUtils.isListEmpty(element['children'])) {
              remoteControlMap = filterByAuthority(element) ?? {};
              if (!FuncUtils.isEmpty(remoteControlMap)) {
                showListString.add(element['name'].toString());
                actionList.add(
                  FuncUtils.getAppBarPopItem(
                      Image.asset(
                        ImageAssets.iconRemoteControl,
                        fit: BoxFit.fill,
                      ),
                      element['name'],
                      0),
                );
              }
            } else if (element['id'] == 'config' &&
                !FuncUtils.isListEmpty(element['children'])) {
              configMap = filterByAuthority(element) ?? {};

              if (!FuncUtils.isEmpty(configMap)) {
                showListString.add(element['name'].toString());
                actionList.add(
                  FuncUtils.getAppBarPopItem(
                      Image.asset(
                        ImageAssets.iconSetting,
                        fit: BoxFit.fill,
                      ),
                      element['name'],
                      1),
                );
              }
            } else if (element['id'] == 'runningData') {
              pageMap = element;
              if (element['children'] != null) {
                List? list = element['children'];
                if (list != null && list.isNotEmpty) {
                  chartId = element['children'][0]['id'];
                }
              }
              subscriptDevices(pageMap);
            }
          }
        }
      }, showLoading: false);

  Future<bool> toService(value) async {
    if (value == 0) {
      /// 远程控制
      await Get.toNamed(RouterPath.deviceControll, arguments: {
        'deviceId': deviceModel!.deviceId,
        'page': remoteControlMap,
        'title': ResKey.remoteControll.tr
      });
    } else if (value == 1) {
      await Get.toNamed(RouterPath.deviceControll, arguments: {
        'deviceId': deviceModel!.deviceId,
        'page': configMap,
        'title': ResKey.deviceParameterSetting.tr
      });
    }
    Get.back();
    return true;
  }

  List setPushData(List? propertyList, Map? data) {
    if (FuncUtils.isListEmpty(propertyList)) {
      return [];
    }
    if (FuncUtils.isListEmpty(data?.keys.toList())) {
      return propertyList!;
    }
    return propertyList!.map((e) {
      if (e['deviceId'] != null) {
        e['id'] = "${e['id']}-${e['deviceId']}";
      } else {
        e['value'] = "${e['id']}-$deviceId";
      }
      return e;
    }).toList();
  }

  /// 订阅设备
  subscriptDevices(Map config) {
    var deviceList =
        DeviceControllUtils.getDeviceIdFromTempl(config['children']);
    streamController = subsribe.start(deviceList, true);
  }

  /// 过滤掉没有“detail”权限的项
  Map? filterByAuthority(Map page) {
    if (FuncUtils.isPassTargetAuthority(page['authority'],
        permissionSource: UserEntityManager().webPermission)) {
      List children = page['children'] ?? [];
      List filtedChildren = [];
      for (var i = 0; i < children.length; i++) {
        var map = filterByAuthority(children[i]);
        if (map != null) {
          filtedChildren.add(map);
        }
      }

      if (!(page['type'] == DeviceConfigType.pageComponent.name ||
              page['type'] == DeviceConfigType.property.name) &&
          (!FuncUtils.isListEmpty(children) &&
              FuncUtils.isListEmpty(filtedChildren))) {
        /// 下级都没有权限，则移除父级
        return null;
      } else {
        page['children'] = filtedChildren;
      }

      return page;
    } else {
      return null;
    }
  }
}
